<template>
	<view class="page_body">
		<!-- 状态栏高度 设置背景色 占位状态栏-->
		<!-- <view class="ztl"
			:style="{'height':statusBarHeight}"></view> -->
		<!-- 占位盒子 -->
		<!-- <view class=""
			:style="{'height': height}"></view> -->
		<!-- 导航栏 -->
		<navBar bgColor="#FFF">
			<image :slot="'left'"
				:src="xcxImgUrl && xcxImgUrl+'fanhui.svg'"
				@click="navToBack"
				style="width: 36rpx;height: 36rpx;">
			</image>
			<text :slot="'content'">品牌专区</text>
		</navBar>

		<!-- 搜索栏 -->
		<view style="background-color: #FFF;">
			<search @searchBlur='searchBlur'
				@nativeInput="nativeInput"
				:isLinks='false'
				bgColor="#F5F5F5">
			</search>
		</view>

		<scroll-view scroll-y
			@scroll="scrollPage"
			:scroll-top="scrollTop"
			:style="{'height': 'calc(100vh -  ' + demoTopHieght +  ');overflow:auto;'}"
			class="mian_brand">
			<view id="scroll">
				<view class="remen">
					<view class="remen-top pd10">
						<image :src="xcxImgUrl && xcxImgUrl+'classitys/remen.svg'"
							style="width: 32rpx;height: 32rpx;"
							mode="aspectFill"
							class="mr10"></image>
						热门品牌
					</view>
					<view class="remen-list">
						<view class="remen-item"
							v-for="(item,index) of top8"
							:key="index"
							@click="toSearch(item)">
							<image :src="item.picture ? uploadImgUrl + item.picture : updateMorentu"
								style="width: 88rpx;height: 88rpx;"
								mode="aspectFill"></image>
							<text>{{item.name}}</text>
						</view>
					</view>
				</view>

				<template v-for="(item, index) in indexList">
					<view :id="item.letter && item.letter.toLowerCase()"
						style="background-color: #f5f5f5;border-bottom:2rpx solid #ddd;height:70rpx;line-height:70rpx;padding-left:20rpx;box-sizing: border-box;">
						{{item.letter}}
					</view>
					<template v-if="item.data && item.data.length">
						<view class="list-cell"
							v-for="(cells, indexs) in item.data"
							:key="indexs"
							@click="toSearch(cells)">
							<image v-if="updateNoneImg"
								:src="cells.picture ? uploadImgUrl + cells.picture : updateMorentu"
								style="width: 68rpx;height: 68rpx;vertical-align: middle;margin-left:40rpx;"
								class="mr10 "
								mode="aspectFill"></image>
							<text :style="{marginLeft:updateNoneImg ? 0 : '30rpx'}">{{cells.name}}</text>
						</view>
					</template>
				</template>
			</view>
		</scroll-view>

		<view class="right_fixed">
			<view v-for="(item,index) of xArr"
				:class="{active:anchorIndex == index}"
				:key="index"
				@click="selectAnchor(item,index)">{{item}}</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import {
		listMallCommodityBrandPageInfo
	} from '@/api/global.js'
	import {
		uploadImgUrl
	} from '@/utils/request.js'
	let datas = [{
			letter: "#",
			data: []
		},
		{
			letter: "A",
			data: []
		},
		{
			letter: "B",
			data: []
		},
		{
			letter: "C",
			data: []
		},
		{
			letter: "D",
			data: []
		},
		{
			letter: "E",
			data: []
		},
		{
			letter: "F",
			data: []
		},
		{
			letter: "G",
			data: []
		},
		{
			letter: "H",
			data: []
		},
		{
			letter: "I",
			data: []
		},
		{
			letter: "J",
			data: []
		},
		{
			letter: "K",
			data: []
		},
		{
			letter: "L",
			data: []
		},
		{
			letter: "M",
			data: []
		},
		{
			letter: "N",
			data: []
		},
		{
			letter: "O",
			data: []
		},
		{
			letter: "P",
			data: []
		},
		{
			letter: "Q",
			data: []
		},
		{
			letter: "R",
			data: []
		},
		{
			letter: "S",
			data: []
		},
		{
			letter: "T",
			data: []
		},
		{
			letter: "U",
			data: []
		},
		{
			letter: "V",
			data: []
		},
		{
			letter: "W",
			data: []
		},
		{
			letter: "X",
			data: []
		},
		{
			letter: "Y",
			data: []
		},
		{
			letter: "Z",
			data: []
		},

	];
	export default {
		computed: {
			...mapGetters(['demoTopHieght']),
			//返回默认图 兼容小程序 直接在html写vuex不生效
			updateMorentu() {
				return this.$store.state.morentu
			},
			//返回有图无图控制
			updateNoneImg() {
				return this.$store.state.configSetting.noneImge == 1 ? false : true
			},
			customNavHeight() {
				console.log(uni.getSystemInfoSync().screenWidth)
				return uni.getSystemInfoSync() && uni.getSystemInfoSync().screenWidth * 0.106;
			}
		},
		data() {
			return {
				allTopArr: [],
				scrollHeight: 0,
				anchorIndex: ``,
				sys: uni.getSystemInfoSync().screenWidth,
				statusBarHeight: '',
				height: '',
				top8: [],
				xArr: ['#', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
					't', 'u', 'v', 'w', 'x', 'y', 'z'
				],
				indexList: [{
						letter: "#",
						data: []
					},
					{
						letter: "A",
						data: []
					},
					{
						letter: "B",
						data: []
					},
					{
						letter: "C",
						data: []
					},
					{
						letter: "D",
						data: []
					},
					{
						letter: "E",
						data: []
					},
					{
						letter: "F",
						data: []
					},
					{
						letter: "G",
						data: []
					},
					{
						letter: "H",
						data: []
					},
					{
						letter: "I",
						data: []
					},
					{
						letter: "J",
						data: []
					},
					{
						letter: "K",
						data: []
					},
					{
						letter: "L",
						data: []
					},
					{
						letter: "M",
						data: []
					},
					{
						letter: "N",
						data: []
					},
					{
						letter: "O",
						data: []
					},
					{
						letter: "P",
						data: []
					},
					{
						letter: "Q",
						data: []
					},
					{
						letter: "R",
						data: []
					},
					{
						letter: "S",
						data: []
					},
					{
						letter: "T",
						data: []
					},
					{
						letter: "U",
						data: []
					},
					{
						letter: "V",
						data: []
					},
					{
						letter: "W",
						data: []
					},
					{
						letter: "X",
						data: []
					},
					{
						letter: "Y",
						data: []
					},
					{
						letter: "Z",
						data: []
					},

				],
				remenList: [],
				pageData: {
					currentPage: 1,
					pageSize: 10
				},
				lastPage: 1, //
				uploadImgUrl,
				search: ``,
				anchorId: ``,
				scrollTop: 0,
				isBottom: false,
				timer: null
			};
		},
		onShow() {
			this.$nextTick(() => {
				// 获取状态栏的高度
				this.statusBarHeight = this.$store.state.statusBarHeight * 2 + 'rpx'
				// 计算站位的高度
				this.height = (this.$store.state.navBarHeight) * 2 + 'rpx'
				//获取高度
				this.Utils.getDemoTopHeight('mian_brand')
			})
		},
		onLoad() {
			this.getList('init') //获取品牌
		},
		methods: {
			scrollPage(e) {
				console.log(e.detail.scrollTop)
				if (e.detail.scrollTop >= this.scrollHeight - uni.getSystemInfoSync().screenHeight + 104) {
					return;
				}
				let topArr = this.allTopArr.map(v => v && v.top).filter(v => v);
				for (let i = 0; i < topArr.length; i++) {
					if (e.detail.scrollTop + 104 >= topArr[i] && e.detail.scrollTop + 104 < topArr[i + 1]) {
						this.anchorIndex = i;
					}
				}
			},
			selectAnchor(v, i) {
				this.anchorIndex = i;
				let index = this.allTopArr.findIndex(a => a && a.id && a.id == v.toLowerCase());
				this.scrollTop = this.allTopArr[index].top - 104;
			},
			searchFn() {
				this.search = ``;
				this.getList();
			},
			searchBlur(e) {
				this.search = e;
				this.getList();
			},
			nativeInput(e) {
				this.search = e;
				clearTimeout(this.timer);
				this.timer = setTimeout(() => {
					this.getList();
				}, 1000)
			},
			//返回上一级
			navToBack() {
				uni.navigateBack()
			},
			selectA() {
				console.log(9)
			},
			//去搜索
			toSearch(item) {
				console.log(this.indexList, 98, item);
				// this.$store.state.searchName = item.name
				uni.navigateTo({
					// url: `/page_public/publicClass?title=搜索`
					url: `/page_public/publicClass?title=搜索&brandId=${item.brandId}&active=3`
				})
			},
			customSort(a, b) {
				const isANumber = !isNaN(a) && !isNaN(b);

				if (isANumber) {
					return parseInt(a) - parseInt(b);
				}

				let index = 0;
				while (index < Math.min(a.length, b.length)) {
					const charA = a[index];
					const charB = b[index];

					if (!isNaN(charA) && !isNaN(charB)) {
						if (charA < charB) return -1;
						if (charA > charB) return 1;
					} else if (isNaN(charA) && isNaN(charB)) {
						if (charA < charB) return -1;
						if (charA > charB) return 1;
					} else if (isNaN(charA)) {
						return 1;
					} else {
						return -1;
					}
					index++;
				}

				return a.length - b.length;
			},
			//获取列表
			async getList(params = '') {
				let query = uni.createSelectorQuery().in(this);
				let _this = this;
				uni.showLoading()
				let res = await listMallCommodityBrandPageInfo({
					sort: 23,
					search: this.search
					// ...this.pageData
				})
				if (res.code == 2000) {
					uni.hideLoading();
					let list = []
					if (params == 'init') {
						this.remenList = (res?.data?.info || []);
						list = res?.data?.info || []
						//取前八
						this.top8 = this.remenList.slice(0, 8)
					} else {
						this.remenList = [];
						this.indexList = JSON.parse(JSON.stringify(datas));
						list = res?.data?.info || []
						this.remenList = (res?.data?.info || []);
					}

					this.lastPage = res?.data?.info?.lastPage;
					console.log(this.top8);
					//每个对象添加拼音 取首字母
					list.forEach((item, index) => {
						if (this.pinyin.chineseToPinYin(item.name)) {
							list[index].pyName = this.pinyin.chineseToPinYin(item.name);
						} else {
							//便于后面排序
							list[index].pyName = item.name;
						}

					})
					//根据首字母排序
					// this.remenList.sort((a, b) => a['pyName'].localeCompare(b['pyName']))
					// 根据首个字符排序 数字（首字符数字相同，比较第二个）和符号在前 字母在后
					this.remenList = list.sort((a, b) => {
						const isANumberA = !isNaN(a.pyName);
						const isANumberB = !isNaN(b.pyName);

						if (isANumberA && !isANumberB) {
							return -1;
						} else if (!isANumberA && isANumberB) {
							return 1;
						} else {
							return this.customSort(a.pyName, b.pyName);
						}
					})
					//查找第一个字符为非字母的索引
					let indexChar = list.length - [...list].reverse().findIndex(function(str) {
						let firstChar = str.pyName.charAt(0);
						return !(/[A-Za-z]/).test(firstChar); // 检查第一个字符是否不是字母
					}) - 1
					console.log('this.remenList', this.remenList);
					//循环数据和字数数组做对比
					for (let i = 0; i < this.remenList.length; i++) {
						if (i <= indexChar) {
							this.indexList[0].data.push(this.remenList[i])
						} else {
							//循环新字母索引 重新组装数据
							for (let j = 0; j < this.indexList.length; j++) {
								//截取第一个 字母 比较
								if (this.remenList[i].pyName.slice(0, 1) == this.indexList[j].letter) {
									console.log(9)
									this.indexList[j].data.push(this.remenList[i])
								}
							}
						}
					}

				}
				setTimeout(() => {
					query.select("#scroll").boundingClientRect().exec((r) => {
						_this.scrollHeight = r[0].height;
					})
					for (let i = 0; i < this.xArr.length; i++) {
						query.select("#" + this.xArr[i]).boundingClientRect().exec((r) => {
							console.log(r)
							_this.allTopArr = r;
						})
					}
				}, 1000)
			}
		}
	}
</script>

<style lang="scss"
	scoped>
	.right_fixed {
		width: 40rpx;
		height: 864rpx;
		font-size: 24rpx;
		position: fixed;
		right: 20rpx;
		top: calc(50% - 432rpx);

		>view {
			width: 32rpx;
			height: 32rpx;
			line-height: 32rpx;
			text-align: center;
		}

		.active {
			color: #fff;
			border-radius: 50%;
			background-color: #ec4141;
		}
	}

	.mian_brand {
		width: 100%;
		box-sizing: border-box;
		background-color: #fff;

		.remen {
			width: 100%;
			// height: 460rpx;
			// border: 1px solid red;
			box-sizing: border-box;
			background: #fff;

			.remen-top {
				height: 60rpx;
				display: flex;
				align-items: center;
				color: $text_color_333;
				font-size: 32rpx;
				font-weight: bold;
			}

			.remen-list {
				display: grid;
				grid-template-columns: repeat(4, 1fr);
				gap: 20rpx;
				padding: 0 20rpx 20rpx 20rpx;

				.remen-item {
					width: 162rpx;
					height: 162rpx;
					border-radius: $border_radius_10;
					border: 1px solid rgba(230, 230, 230, 1);
					;
					background-color: rgba(255, 255, 255, 1);
					box-sizing: border-box;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					font-size: $font_size_12;
					color: $text_color_333;
				}
			}
		}

		/deep/.u-index-list__letter {
			top: 200rpx !important;
		}

		/* #ifndef MP-WEIXIN */
		/deep/.u-index-list uni-scroll-view {
			height: calc(100vh - 88rpx - 88rpx) !important;
			max-height: 100% !important;
		}

		/* #endif */
		/* #ifdef MP-WEIXIN */
		/deep/.u-index-list scroll-view {
			height: calc(100vh - 88rpx - 88rpx - 40rpx) !important;
			max-height: 100% !important;
		}

		/* #endif */

		/deep/.u-transition {
			position: relative !important;
		}
	}
</style>